package billrestauration.secrity.encoder;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordEncoder {
private String algo;
private boolean  encodebase64;
private  int repeat;
private String salt;
public String encode(String rawpassword)  {
	String mes=null;
	if(null==rawpassword)throw new NullPointerException(" the password must not be null");
	try {
		MessageDigest digest=MessageDigest.getInstance(this.algo);
		byte[] initbyte=null;
		if(null!=salt)
		{byte[] a=rawpassword.getBytes(),
		       b=salt.getBytes();
			initbyte=new byte[a. length+b.length];
			int j=0;
			 for(int i=0;i<a.length;i++)
				 initbyte[j++]=a[i];
			 for(int i=0;i<b.length;i++)
				 initbyte[j++]=b[i];
				 
		}else
			initbyte=rawpassword.getBytes();
		byte[] res=digest.digest(initbyte);
		 for(int i=1;i<repeat;i++)
			 res=digest.digest(res);
			 
		if(encodebase64){
			res=org.apache.commons.codec.binary.Base64.encodeBase64(res) ;
			mes=new String(res);
		}else
		mes= byte2HexString(res);
	} catch (NoSuchAlgorithmException e) {
		// TODO Auto-generated catch block
		 throw new IllegalArgumentException("l'algorithme "+algo+" n'est pas supporté!!");
	}
	return mes;
	
}
 
public int getRepeat() {
	return repeat;
}

public void setRepeat(int repeat) {
	this.repeat = repeat;
}

public String getSalt() {
	return salt;
}

public void setSalt(String salt) {
	this.salt = salt;
}

private String byte2HexString(byte[] res) {
	// TODO Auto-generated method stub
	String ress="";
	for (byte b : res) {
		int i;
		if((128&b)==128)i=b+256;
		else
			i=b;
		if(i<16)
		ress+="0"+Integer.toHexString(i);
		else
			ress+=Integer.toHexString(i);	
			
	}
	return ress;
}

public String getAlgo() {
	return algo;
}
public PasswordEncoder() {
	this("SHA-512",true,1,null);
}
public PasswordEncoder(String algo, boolean encodebase64, int repeat,
		String salt) {
	super();
	this.algo = algo;
	this.encodebase64 = encodebase64;
	this.repeat = repeat;
	this.salt = salt;
}

public PasswordEncoder(String algo) {
	 this(algo,true,1,null);
}
public PasswordEncoder(String algo, boolean encodebase64) {
	 
	this(algo,encodebase64,1,null);
}
public void setAlgo(String algo) {
	this.algo = algo;
}
public boolean isEncodebase64() {
	return encodebase64;
}
public void setEncodebase64(boolean encodebase64) {
	this.encodebase64 = encodebase64;
}

@Override
public String toString() {
	return "PasswordEncoder [algo=" + algo + ", encodebase64=" + encodebase64
			+ ", repeat=" + repeat + ", salt=" + salt + "]";
}

 
}
